package com.jfirer.mvc.core.action;

import com.jfirer.jfire.core.ApplicationContext;
import com.jfirer.mvc.annotation.RequestMapping;
import com.jfirer.mvc.config.MvcConfig;
import com.jfirer.mvc.core.route.RouteTree;
import com.jfirer.mvc.core.route.Router;
import com.jfirer.mvc.core.route.impl.RouteTreeImpl;

import javax.servlet.http.HttpServletRequest;

public final class ActionCenter
{
    private final RouteTree          routeTree = new RouteTreeImpl();
    private final MvcConfig          mvcConfig;

    public ActionCenter(Action[] actions, ApplicationContext context)
    {
        mvcConfig = context.getBean(MvcConfig.class);
        for (Action each : actions)
        {
            String   url         = each.getRequestUrl();
            String   name        = each.getName();
            String[] headerRules = each.getHeaderRules();
            for (RequestMapping.RequestMethod requestMethod : each.getRequestMethods())
            {
                routeTree.resolve(name, url, requestMethod.name(), headerRules).bindAction(each);
            }
        }
        routeTree.finishResolve();
    }

    public Action getAction(HttpServletRequest request)
    {
        String path   = request.getRequestURI();
        Router router = routeTree.route(path, request);
        return router != null ? router.bindedAction() : null;
    }

    public MvcConfig mvcConfig()
    {
        return mvcConfig;
    }

}
